import global from './config.js' //全局配置
function wxPay(data) {
	//微信公众号支付
	function onBridgeReady() {
		WeixinJSBridge.invoke(
			'getBrandWCPayRequest', {
				...data,
				// "appId": data.appid, //公众号名称，由商户传入     
				// "timeStamp": data.times, //时间戳，自1970年以来的秒数     
				// "nonceStr": data.nonce_str, //随机串     
				// "package": "prepay_id=u802345jgfjsdfgsdg888",
				// "signType": "RSA", //微信签名方式：     
				// "paySign": data.sign //微信签名 
			},
			function(res) {
				if (res.err_msg ==
					"get_brand_wcpay_request:ok") {
					// msg(res.msg)
					return res
				} // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。 
			}
		);
	}
	if (typeof WeixinJSBridge == "undefined") {
		if (document.addEventListener) {
			document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
		} else if (document.attachEvent) {
			document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
			document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
		}
	} else {
		onBridgeReady();
	}
}

function pay(orderInfo, type) {
	//例如：	// this.$tool.pay(orderInfo,'alipay')
	params = {
		orderInfo,
		provider: type, //alipay 支付宝  appleiap苹果   wxpay 微信
	}
	if (type == 'wechat') {
		// #ifdef APP-PLUS 
		//APP微信支付 
		params.orderInfo = JSON.parse(orderInfo)
		params.provider = 'wxpay'
		// #endif
		// #ifdef MP-WEIXIN
		//微信小程序支付
		params = orderInfo
		// #endif
		// #ifdef H5
		let ua = window.navigator.userAgent.toLowerCase();
		if (ua.indexOf('micromessenger') != -1) { //微信公众号
			return wxPay()
		}
		// #endif
	}
	return new Promise((resolve, reject) => {
		uni.requestPayment({
			...params,
			success: res2 => {
				console.log(res2);
				resolve(res2)
			},
			fail: (res2) => {
				console.log(res2);
				reject(res2)
			},
			complete: (res2) => {}
		});
	})
}

function msg(title, duration = 1500, mask = false, icon = 'none') {
	//统一提示方便全局修改
	if (Boolean(title) === false) {
		return;
	}
	uni.showToast({
		title,
		duration,
		mask,
		icon
	});
}

function copy(data, msg1 = '复制成功', msg2 = '复制失败') {
	uni.setClipboardData({
		data,
		success: function() {
			msg(msg1)
		},
		fail() {
			msg(msg2)
		}
	});
}



function phone(phoneNumber) {
	//打电话
	console.log('打电话', phoneNumber);
	msg('打电话: ' + phoneNumber)
	uni.makePhoneCall({
		phoneNumber,
	})
}

function lookImg(urls, current = 0) {
	// 预览图片
	// console.log(urls, current);
	uni.previewImage({
		urls,
		current,
		// indicator:true,
	});
}

function setTit(title) {
	uni.setNavigationBarTitle({
		title,
	})
}

function saveImg(filePath) {
	// #ifdef H5
	msg('长按图片保存')
	// #endif
	// #ifndef H5
	uni.saveImageToPhotosAlbum({
		filePath,
		success(res) {
			msg('保存成功')
			console.log(errMsg);
		}
	})
	// #endif
}

function screenshot() { //app 绘制页面并保存图片
	// #ifdef APP-PLUS
	var pages = getCurrentPages();
	var page = pages[pages.length - 1];
	console.log("当前页" + pages.length - 1);
	var bitmap = null;
	var currentWebview = page.$getAppWebview();
	bitmap = new plus.nativeObj.Bitmap('amway_img');
	// 将webview内容绘制到Bitmap对象中  
	currentWebview.draw(bitmap, function() {
		console.log('截屏绘制图片成功');
		bitmap.save("_doc/a.jpg", {}, function(i) {
			console.log('保存图片成功：' + JSON.stringify(i));
			uni.saveImageToPhotosAlbum({
				filePath: i.target,
				success: function() {
					bitmap.clear(); //销毁Bitmap图片  
					uni.showToast({
						title: '保存图片成功',
						mask: false,
						duration: 1500
					});
				}
			});
		}, function(e) {
			console.log('保存图片失败：' + JSON.stringify(e));
		});
	}, function(e) {
		console.log('截屏绘制图片失败：' + JSON.stringify(e));
	});
	// #endif
	// #ifndef APP-PLUS
	uni.showToast({
		title: '请在app内使用该功能,或手动截屏',
		mask: false,
		duration: 1500,
		icon: 'error'
	});
	// #endif
}

function showModal(title = '', content, showCancel = true) { //二次确认筐
	return new Promise(function(resolve, err) {
		uni.showModal({
			title: content ? title : '提示',
			content: content ? content : ('确认' + title + '吗'),
			showCancel,
			success(res) {
				if (res.confirm) {
					resolve()
				} else {
					err('取消')
				}
			}
		})
	})
}

function refresh() { //刷新页面
	return new Promise((resolve, reject) => {
		let pages = getCurrentPages()
		let page = pages[pages.length - 1]
		let url = decodeURI(page?.$page?.fullPath)
		url = url[0] === '/' ? url : `/${url}`
		uni.redirectTo({
			url,
			success() {
				return resolve('刷新成功')
			},
			fail(res) {
				uni.reLaunch({
					url,
					success() {
						return resolve('刷新成功')
					},
					fail() {
						return reject('刷新失败')
					}
				})
			}
		})
	})
}


function splitArr(arr, size = 2) { //一维数组分割多个数组
	let array = deepClone(arr)
	if (!isArray(array)) return []
	let data = [];
	for (let i = 0; i < array.length; i += size) {
		data.push(array.slice(i, i + size))
	}
	return data
}


function sjump(url) {
	//跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面
	uni.switchTab({
		url
	})
}

//返回页面
function navBack(delta = 1, time = 0) {
	time ? setTimeout(navigateBack, time) : navigateBack()
	function navigateBack() {
		let getPage = getCurrentPages()
		if (getPage.length == 1) {
			uni.switchTab({
				url: '/pages/index/index'
			})
		} else {
			//关闭当前页面，返回上一页面或多级页面
			uni.navigateBack({
				delta
			})
		}
	}
}
//关闭所有页面，打开到应用内的某个页面
function reUrl(url) {
	uni.reLaunch({
		url
	})
}
//关闭当前页面，跳转到应用内的某个页面
function rjump(url) {
	uni.redirectTo({
		url
	})
}
//是否是数组
function isArray(arr) {
	return Object.prototype.toString.call(arr) === '[object Array]';
}
// 深度克隆
function deepClone(obj) {
	// 对常见的“非”值，直接返回原来值
	if ([null, undefined, NaN, false].includes(obj)) return obj;
	if (typeof obj !== "object" && typeof obj !== 'function') {
		//原始类型直接返回
		return obj;
	}
	var o = isArray(obj) ? [] : {};
	for (let i in obj) {
		if (obj.hasOwnProperty(i)) {
			o[i] = typeof obj[i] === "object" ? deepClone(obj[i]) : obj[i];
		}
	}
	return o;
}
//oss图片截取
function oss(url, time = 1) {
	return url + `?x-oss-process=video/snapshot,t_${time},m_fast`
}
//多图单图处理拼接链接
function showActionSheet(arr) { //操作列表
	if (!arr.length) return
	uni.showActionSheet({
		itemList: arr.map(e => e.name),
		success(res) {
			arr[res.tapIndex].fn?.()
		}
	})
}
//对象转路径
function objToUrl(url, params) {
	for (let key in params) {
		if ((params[key] ?? '') === '') continue
		url.indexOf('?') == -1 ? url += '?' : url += '&'
		url += key + '=' + params[key]
	}
	return url
}
//调用第三方程序打开指定的URL
function openLink(href, mpTips = "链接已复制，请在浏览器打开") {
	if (!href) return
	// #ifdef APP-PLUS
	plus.runtime.openURL(href)
	// #endif
	// #ifdef H5
	window.open(href)
	// #endif
	// #ifdef MP
	uni.setClipboardData({
		data: href,
		success: () => {
			uni.hideToast();
			this.$nextTick(() => {
				msg(mpTips);
			})
		}
	});
	// #endif
}
//局内跳转
function jump(options = '', params = '', type = 'navigateTo') {
	let config = {
		url: options,
		params,
		type
	}
	if (typeof options !== 'string') {
		config = {
			...config,
			...options
		}
	}
	config.url = objToUrl(config.url, config.params)
	let fnobj = {
		url: config.url,
		fail() {
			uni.switchTab({
				url: config.url,
				fail() {
					console.log('跳转失败:', config, 'mergeConfig');
				}
			})
		}
	}
	if (['navigateTo', 'to'].includes(config.type)) {
		uni.navigateTo(fnobj);
	} else if (['redirectTo', 'redirect', 're'].includes(config.type)) {
		uni.redirectTo(fnobj);
	} else if (['reLaunch', 'launch', 'rel'].includes(config.type)) {
		uni.reLaunch(fnobj);
	} else {
		uni[obj.type](fnobj)
	}
}

function advJump(data) {
	let url = data && data?.link || data?.url || ''
	if (!url) return console.log('跳转链接为"url",参数为"params"', data);
	if (url.startsWith(global.baseUrl)) {
		url = url.split('/#')[1]
		jump(url, data.params)
	} else if (url.startsWith('http')) {
		openLink(url)
	} else {
		jump(url, data.params)
	}
}

function objList(arr) { //一维数组分割多个数组
	return arr?.map(e => {
		return {
			label: e
		}
	}) || ''
}

function paths(paths) {
	let arr = paths
	if (!Array.isArray(paths)) arr = [paths]
	console.log(arr);
	return arr
}
export default {
	pay, //支付
	msg, //提示
	copy, //复制文字
	phone, //打电话
	setTit, //设置标题
	saveImg, //保存图片
	lookImg, //查看图片
	showModal, //二次确认框
	refresh, //刷新页面
	wxPay, //微信公众号支付
	objToUrl, // 对象路由
	screenshot, //保存截图
	splitArr, //一维数组分割多个数组
	deepClone, // 深度克隆
	oss, //oss图片截取
	paths, //多图单图处理拼接链接
	openLink, // 打开第三方链接链接
	reUrl, //路由跳转  关闭所有页面
	sjump, //路由跳转 tabar  关闭非tabbar页面
	rjump, //路由跳转  关闭当前页面
	navBack, //页面返回
	jump, //局内跳转
	advJump, //保留当前页面，跳转到应用内的某个页面
	jumps: advJump, //保留当前页面，跳转到应用内的某个页面
	showActionSheet, //
	objList,
}